import {
    wechatLogin,
    userinfo,
    logout,
} from "./request/api"
App({
	async onShow(e) { //小程序启动，或从后台进入前台显示时触发
        //版本是否更新
        this.updata();
        //获取openid 和 获取session_key 的值
        await this.loginIn()
    },

    //方法
    async loginIn() {
        let that = this
        wx.login({
            complete: async (res) => {
				let code = res.code
                try {
                    let login = await wechatLogin({
                        code
                    })
                    if (login.code == 200) {
						let openid = login.data.openid
                        if (openid) {
                            this.globalData.openid = openid
                        }
                    }else{
                        wx.redirectTo({
                            url: '/pages/login/login',
                        })
                    }
                } catch (error) {
                    //清除缓存数据
                    let removelist
                    for (const item of removelist) {
                        wx.removeStorageSync(item)
                    }
                }
            }
        })
    },


//退出登录
    async logout() {
        let userid=wx.getStorageSync('userid')
        let res = await logout({
            userid: userid
        })
        if (res.code == 200) {
            setTimeout(() => {
                wx.clearStorageSync();
                wx.redirectTo({
                    url: '/pages/Login/Login',
                })
            }, 2000)
        }
    },


    //获取用户的信息
    async userinfo() {
        let that=this
        const pages = getCurrentPages(); // 获取当前页面栈
        const currentPage = pages[pages.length - 1].route; // 获取当前页面实例
        let routerlist=['PackageCancellation/page/Student_work/index','PackageClass/page/Student_work/index','PackageStudent/page/Details_works/index','PackageClass/page/Class_management/index','PackageCancellation/page/index/index',"PackageTeacherHome/page/studentDetails/studentDetails"]
        let res = await userinfo()
        if (res.code == 200) {
            if(res.data.length>0){
                const role_id = res.data[0].role_id //角色id
                const trainee = res.data[0].id //学员id
                const userInfo =res.data[0]
                const userid=res.data[0].user_id
                if(!routerlist.includes(currentPage)){
                    if (res.data[0].role_id == 6) { //老师
                        wx.switchTab({
                            url: '/pages/t-home/t-home',
                        })
                    }
                    if (res.data[0].role_id == 7) { //学生
                        if (res.data.length > 1) { //多个
                            wx.redirectTo({
                                url: '/commonality/page/Account/index',
                            })
                        } else {
                            wx.switchTab({
                                url: '/pages/Course_schedule/Course_schedule',
                            })
                        }
                    }
                    wx.setStorageSync('role_id', role_id)
                    wx.setStorageSync('trainee', trainee)
                    wx.setStorageSync('userInfo', userInfo)
                    wx.setStorageSync('userid', userid)
                }
            }else{
                wx.showModal({
                    title: '温馨提示',
                    content: '您的账号登录过期，请重新登录',
                    showCancel: false,
                    confirmColor: "#5677FC",
                    success: function (res) {
                        that.logout()
                    }
                })

            }
        }
    },






    //小程序的跟新机制加兼容
    updata() {
        if (wx.canIUse('getUpdateManager')) {
            const updateManager = wx.getUpdateManager()
            updateManager.onCheckForUpdate(function (res) {
                // 请求完新版本信息的回调
                if (res.hasUpdate) {
                    updateManager.onUpdateReady(function () {
                        wx.showModal({
                            title: '更新提示',
                            content: '新版本已经上线啦~，为了获得更好的体验，建议立即更新',
                            showCancel: false,
                            confirmColor: "#5677FC",
                            success: function (res) {
                                // 新的版本已经下载好，调用 applyUpdate 应用新版本并重启
                                updateManager.applyUpdate()
                            }
                        })
                    })
                    updateManager.onUpdateFailed(function () {
                        // 新的版本下载失败
                        wx.showModal({
                            title: '更新失败',
                            content: '新版本更新失败，为了获得更好的体验，请您删除当前小程序，重新搜索打开',
                            confirmColor: "#5677FC",
                            showCancel: false
                        })
                    })
                }
            })
        } else {
            // 当前微信版本过低，无法使用该功能
        }
    },

    //小程序初始化完成时触发，全局只触发一次
    onLaunch: function () {},

    onHide: function () { //小程序从前台进入后台时触发

    },
    onError: function () { //小程序发生脚本错误或 API 调用报错时触发

    },
    onPageNotFound: function () { //小程序要打开的页面不存在时触发

    },
    onUnhandledRejection: function () { //小程序有未处理的 Promise 拒绝时触发

    },
    onThemeChange: function () { //系统切换主题时触发

    },


    //公共的版本信息
    globalData: {
		access_token: '', //获取token信息
		openid:'',
        version: "1.0.0", //版本信息
    },
})